package com.gitee.form_token.service.impl;

import com.gitee.form_token.common.Const;
import com.gitee.form_token.token.CheckAppToken;
import com.gitee.form_token.common.RedisUtil;
import com.gitee.form_token.dto.LoginDto;
import com.gitee.form_token.entity.AppUser;
import com.gitee.form_token.mapper.AppUserMapper;
import com.gitee.form_token.service.AppUserService;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author Saturn
 * @since 2024-11-01
 */
@Service
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> implements AppUserService {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private HttpServletRequest httpRequest;

    @Override
    public AppUser login(LoginDto loginDto) {

        AppUser appUser = this.getOne(new QueryWrapper<AppUser>()
                .select("id", "username", "password", "tel", "last_login", "avatar")
                .eq("username", loginDto.getUsername())
        );

        // 校验账号密码
        Assert.notNull(appUser, "账号不存在");

        String md5Password = SecureUtil.md5(loginDto.getPassword());
        Assert.isTrue(appUser.getPassword().equals(md5Password), Const.loginErrorMsg);

        // 最后登录时间
        appUser.setLastLogin(LocalDateTime.now());
        this.updateById(appUser);

        return appUser;
    }

    @Override
    public AppUser getCurrentUser() {
        return this.getById(getCurrentUserId());
    }

    @Override
    public long getCurrentUserId() {

        // Token校验
        String username = CheckAppToken.getSubject(httpRequest);
        String redisKey = "app_" + username;

        AppUser appUser = (AppUser) redisUtil.get(redisKey);
        if (appUser == null) {
            throw new RuntimeException("redis读取null");
        }

        return appUser.getId();
    }

}
